import type { ActionWithPayload } from "redux"
import { authLs } from "@/utils/auth"
import {
  RESET,
  CLEARUSERINFO,
  UPDATETOKEN,
  UPDATEUSERINFO,
  RECEIVESTATE,
  UPDATEEXTRA
} from "../actionTypes/auth"

/** helper for generate initial state for store */
function getInitialState(): IAuthStore {
  return {
    userInfo: authLs.getUserInfo(),
    token: authLs.getToken(),
    extra: authLs.getExtra()
  }
}

/**
 * redux msgTemplate store
 * @param {IAuthStore} state store state
 * @param {Action} action action
 * @returns store
 */
export default function (state = getInitialState(), action: ActionWithPayload): IAuthStore {
  switch (action.type) {
    case RESET:
      return getInitialState()
    case CLEARUSERINFO:
      return {
        ...state,
        userInfo: {}
      }
    case UPDATEUSERINFO:
      return {
        ...state,
        userInfo: {
          ...state.userInfo,
          ...action.payload
        }
      }
    case UPDATEEXTRA:
      return {
        ...state,
        extra: {
          ...state.extra,
          ...action.payload
        }
      }
    case RECEIVESTATE:
      return {
        ...action.payload,
        extra: state.extra
      }
    case UPDATETOKEN:
      return {
        ...state,
        token: action.payload
      }
    default:
      return state
  }
}
